package com.kehutong.repair.service.admin;

import com.kehutong.repair.entity.RepairsType;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;

import java.util.List;

@WebService("/repairs/admin/type/service")
public class AdminRepairsTypeService {

    static final Logger logger = LoggerFactory.getLogger(AdminRepairsTypeService.class);

    @Inject
    private JdbcSession jdbcSession;

    @ReqMapping("/list")
    public Page<RepairsType> list(JSONObject jsonObject) {
        return jdbcSession.findPage(RepairsType.class)
                .eq(jsonObject, "id", "pid", "name", "companyNo", "type")
                .eq("deleted", false)
                .order("type", "desc")
                .page(jsonObject)
                .exe();
    }

    @ReqMapping("/allList")
    public Object allList(JSONObject jsonObject) {
        return jdbcSession.findArray(RepairsType.class)
                .eq(jsonObject, "companyNo", "type", "pid")
                .eq("deleted", false).exe();
    }

    @ReqMapping("/get")
    public RepairsType get(String id){
        return Pool.get(RepairsType.class, id);
    }

    @Bean(newInstance = true, copy = true)
    @ReqMapping("/save")
    public Object save(RepairsType repairsType) {
        jdbcSession.insert(repairsType);
        return Result.success();
    }

    @Bean(copy = true)
    @ReqMapping("/update")
    public Object update(RepairsType repairsType) {
        jdbcSession.updateById(repairsType);
        return Result.success();
    }

    @ReqMapping("/delete")
    public Object delete(String id) {
        RepairsType item = Pool.get(RepairsType.class, id);
        List<RepairsType> repairsTypes = jdbcSession.findArray(RepairsType.class)
                .eq("pid", item.getId())
                .eq("deleted", false).exe();

        if (repairsTypes.size() != 0) {
            return Result.error(-1, item.getName() + "存在下级分类，请先删除下级分类！");
        }

        item.setDeleted(true);
        jdbcSession.updateById(item);
        return Result.success(item);
    }
}
